package com.gcpproxy.auth;

import com.gcpproxy.config.AppConfig;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Bearer Token认证过滤器
 */
public class BearerTokenAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(BearerTokenAuthenticationFilter.class);
    private static final String BEARER_PREFIX = "Bearer ";
    
    // 白名单路径
    private static final List<String> WHITELIST_PATHS = Arrays.asList(
        "/health",
        "/v1/models"
    );

    private final AuthenticationManager authenticationManager;
    private final AppConfig appConfig;

    public BearerTokenAuthenticationFilter(AuthenticationManager authenticationManager, AppConfig appConfig) {
        this.authenticationManager = authenticationManager;
        this.appConfig = appConfig;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        String path = request.getRequestURI();
        
        // 检查路径是否在白名单中
        if (isWhitelistPath(path)) {
            logger.debug("路径 {} 在白名单中，跳过认证", path);
            filterChain.doFilter(request, response);
            return;
        }

        // 如果认证被禁用，直接通过
        if (!appConfig.getAuth().isEnabled()) {
            logger.debug("认证已禁用，跳过token验证");
            filterChain.doFilter(request, response);
            return;
        }

        try {
            String token = extractTokenFromRequest(request);
            
            if (StringUtils.hasText(token)) {
                BearerTokenAuthentication authRequest = new BearerTokenAuthentication(token, null);
                Authentication authResult = authenticationManager.authenticate(authRequest);
                SecurityContextHolder.getContext().setAuthentication(authResult);
                logger.debug("请求 {} 认证成功", path);
            } else {
                logger.warn("请求 {} 缺少Authorization头或token", path);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"error\":\"缺少Authorization头\"}");
                return;
            }
        } catch (AuthenticationException e) {
            logger.warn("请求 {} 认证失败: {}", path, e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"error\":\"" + e.getMessage() + "\"}");
            return;
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中提取token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.hasText(authHeader)) {
            if (authHeader.startsWith(BEARER_PREFIX)) {
                return authHeader.substring(BEARER_PREFIX.length());
            } else {
                // 支持直接传token（不带Bearer前缀）
                return authHeader;
            }
        }
        return null;
    }

    /**
     * 检查路径是否在白名单中
     */
    private boolean isWhitelistPath(String path) {
        return WHITELIST_PATHS.stream().anyMatch(path::startsWith);
    }
}